package com.zxy.house.config;

import com.alibaba.fastjson.JSONObject;
import com.zxy.house.dao.HouseDao;
import com.zxy.house.entity.HouseEntity;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MyRun implements ApplicationRunner {

    @Autowired
    private HouseDao houseDao;

    @Autowired
    private RestHighLevelClient client;

    //es 添加
    @Override
    public void run(ApplicationArguments args) throws Exception {

        //查询所有数据
        List<HouseEntity> houseEntityList = houseDao.selectList( null );

        BulkRequest bulkRequest = new BulkRequest("house");

        for (HouseEntity houseEntity : houseEntityList) {
            IndexRequest request = new IndexRequest();
            request.id( String.valueOf( houseEntity.getHid() ) );
            String jsonString = JSONObject.toJSONString( houseEntity );
            request.source(jsonString, XContentType.JSON);
            bulkRequest.add( request );
        }

        BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);

        System.out.println("数据同步成功");

    }

}
